//对于axios进行二次封装
import axios from "axios";
//引入进度条 nprogress代表进度条的意思
import nProgress from "nprogress";
//引入store
import store from '@/store'
//引入样式
import 'nprogress/nprogress.css'
import { Message } from "element-ui";
import router from "@/router";
const requests = axios.create({
    //配置对象，发请求的时候路径当中会出现api
    baseURL:'/',
    timeout:5000,

})
//请求拦截器,发请求之前，可以检测到
requests.interceptors.request.use((config)=>{
    // 判断用户是否携带token信息
    if (store.state.login.token) {
        config.headers.token = store.state.login.token
        //设置统一请求头
        config.headers.Authorization = store.state.login.token
    }
     //进度条开始
    nProgress.start();
    return config;
})

//相应拦截器
requests.interceptors.response.use((res)=>{
    if (res.data.message == '身份认证失败！') {
        Message.error('token失效,请重新登录！')
        localStorage.removeItem('TOKEN')
        router.push('/login')
    }
    //进度条结束
    nProgress.done();
    return res.data;
},(error)=>{
    return Promise.reject(new Error('faile'))
})

export default requests;